import React from 'react'
import { DatePicker, Input, notification } from 'antd'
import moment from 'moment'
import './age.css'
const dateFormat = 'YYYY-MM-DD';


export default class Age extends React.Component {

    constructor(props) {
        super(props)
        this.state = {
            age: ''
        }
    }

    infoNotification = (type) => {
        notification[type]({
            message: '日期不能大于今天',
            description: '日期有误',
            duration: 3
        });
    }

    dateChange = (date) => {
        if(date) {
            const now = parseInt(new Date().getTime());
            const dateTime = parseInt(new Date(date).getTime());
            const age = Math.floor((now-dateTime)/(365*24*60*60*1000));
            if(age<0) {
                this.infoNotification('error');
                this.setState({age : 0});
            } else {
                this.setState({age : age});
            }
            
        }
    }

    render() {
        return (
            <div>
                出生日期：
                <DatePicker 
                    defaultValue={moment('2017/08/28', dateFormat)} 
                    format={dateFormat} 
                    placeholder="出生日期" 
                    onChange={this.dateChange}
                />
                <br/>
                <Input addonBefore="你已经" addonAfter="岁了！" value={this.state.age} readOnly/>
            </div>
            
        )
    }
}